import absevnt from '../abseventsvc.js'
import {LGXEnums}  from '../../canvas/common/sysenum.js';
import lgxcom from '../../canvas/common/common.js'
import globalConst from '../../canvas/common/globalConst.js';
import ImageInfo from '../../canvas/common/struct/basestruct/ImageInfo.js';

class ImportImageSvc extends absevnt.IEventSvc {
    constructor() {
        super();
    }

    act(e) {
        console.log("EditTextSvc:xxx---------");
        window.mainctl.setMapWorkMode(LGXEnums.LGXWorkMode.ModifyMode);
        var maitype = globalConst.GlobalConst.BaseUnitImage;
        maitype = maitype << 16;
        var imageUnitInfo = null;
        if (e.gid > 0) {
            imageUnitInfo = window.mainctl.m_pGetDataINTF.getGraphInfo(maitype, e.gid);
        }

        if (!imageUnitInfo) {
            return;
        }
        this.importImg(imageUnitInfo);
    }

    selectFile(accept, formatArr) {
        return new Promise((resolve, reject) => {
            const fileInput = document.createElement('input')
            fileInput.type = 'file';
            fileInput.accept = accept;
            fileInput.click();
            fileInput.onchange = function (event) {
                const file = event.target.files[0]
                if (!formatArr.includes(file.type)) {
                    reject({ message: false, event })
                } else {
                    resolve({ message: true, event, file })
                }
            }
        });
    }


    // 导入图片
    importImg(imageUnitInfo) {
        let that = this;
        const accept = '.png,.jpg,.jpeg,.svg,.json';
        const formatArr = ['image/png', 'image/jpg', 'image/jpeg', 'svg/svg','application/json'];
        this.selectFile(accept, formatArr).then(res => {
            const file = res.file;
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                let imageBase64 = e.target.result;
                //   const reg = new RegExp(';base64');
                //   imageBase64 = imageBase64.replace(reg, '');
                console.log(imageBase64);
                imageUnitInfo.contentBs64 = imageBase64;
                window.mainctl.m_pEditINTF.modifyGraphDataByStru(imageUnitInfo);
            };
        })
            .catch((e) => {
                window.$message.error('仅支持' + accept + '格式的图片')
            })
    }

}

export default { ImportImageSvc }